import { Inject } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { REQUEST } from "@nestjs/core";
import { TypeOrmModuleOptions, TypeOrmOptionsFactory } from "@nestjs/typeorm";


export class TypeOrmConfigService implements TypeOrmOptionsFactory {

    constructor(
        @Inject(REQUEST) private request: Request,
        private readonly configService: ConfigService
    ) { }


    createTypeOrmOptions(connectionName?: string): Promise<TypeOrmModuleOptions> | TypeOrmModuleOptions {
        const headers = this.request.headers
        const tenantId = headers['x-tenant-id']

        let config: any = {
            port: 3306
        }
        const envConfig = {
          type: this.configService.get('DB_TYPE'),
          username: this.configService.get('DB_USERNAME'),
          password: this.configService.get('DB_PASSWORD'),
          host: this.configService.get('DB_HOST'),
          port: this.configService.get('DB_PORT'),
          database: this.configService.get('DB_DATABASE'),
          entities: [__dirname + '/**/*.entity{.ts,.js}'],
          synchronize: Boolean(this.configService.get('DB_SYNC')),
          retryDelay: 500,
          retryAttempts: 10,
          autoLoadEntities: Boolean(this.configService.get('DB_AUTOLOAD')),
        }

        if (tenantId.includes('mysql')) {
            config = {
                port: 3306
            }
        } else if (tenantId.includes('postgresql')) {
            config = {
                type: 'postgresql',
                port: 5432,
                usename: 'pguser',
                database: 'testdb'
            }
        }

        const finialConfig = {...envConfig, ...config}
        return finialConfig
    }

}